package app.biz.model;

import app.framework.common.Errors;
import app.framework.common.Status;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.SocketTimeoutException;

/** ECG请求结果对象 */
public class EcgResponse {
  private static final Logger logger = LoggerFactory.getLogger(EcgResponse.class);
  static final String STATUS = "status";
  static final String RESULT = "result";
  static final String SID = "sid";
  static final String ERROR = "error";
  static final String CODE = "code";

  public JSONObject getResult() {
    return result;
  }

  private JSONObject result;

  public static EcgResponse instance = new EcgResponse();

  /**
   * 异步调用结果返回
   *
   * @param sid
   * @return
   */
  public JSONObject success(long sid) {
    JSONObject result = new JSONObject();
    result.put(STATUS, Status.OK.value());
    result.put(SID, sid);
    this.result = result;
    return result;
  }

  /**
   * 同步调用结果返回
   *
   * @param sid
   * @param result
   * @return
   */
  public JSONObject success(long sid, JSONObject result) {
    String status = result.getString(STATUS);
    result.put(STATUS, status);
    // 调用结果正确
    if (Status.OK.value().equals(status)) {
      result.put(RESULT, result.get(RESULT));
      result.put(SID, sid+"");
    }
    // ECG服务调用结果错误
    else {
      result.put(ERROR, result.get(ERROR));
      result.put(CODE, result.get(CODE));
    }
    this.result = result;
    return result;
  }

  public JSONObject failure(Exception e) {
    JSONObject result = new JSONObject();
    logger.error("ECG服务调用失败!", e.getMessage() );
    result.put("status", Status.ERROR.value());
    if (e instanceof SocketTimeoutException) {
      result.put("code", Errors.TIMEOUT.value());
      result.put("error", "ECG服务调用超时: " + e.getMessage());
    }
    result.put("code", Errors.OTHER.value());
    result.put("error", "ECG服务调用失败: " + e.getMessage());
    this.result = result;
    return result;
  }

  @Override
  public String toString() {
    return this.getResult().toJSONString();
  }
}
